<?php
/**
 * 用户的积分相关的处理函数
 */
require_once '../dr-config.php';
require_once ABSPATH . DRINC . '/dr-functions.php';

require_once ABSPATH . DRINC . '/dr-fun-users.php';
require_once ABSPATH . DRINC . '/dr-fun-histories.php';

/**
 * 获得动作与积分的对应关系
 */
function dr_get_reputation_settings()
{
	$posts = array('action' => 'get_reputation_settings');
	$json_result = dr_server_request('dr-app-reputations.php', $posts);
	return json_decode($json_result, true);
}

/**
 * 计算所有用户的积分值
 */
function dr_calculate_reputation_of_all()
{
	# 获得系统的积分设置
	$rep_settings = dr_get_reputation_settings();
	# 获得所有用户的id以及他们的历史信息
	$users = dr_get_all_user_histories_stats();
	# 计算每一个用户的积分值
	foreach ($users as $user_histories) {
		dr_calculate_reputation_with_userid($user_histories['user_id'], $rep_settings, $user_histories);
	}
}

/**
 * 计算单个用户的当前积分值
 *
 * @param int $userid 用户的id
 * @param array $rep_settings 系统的积分设置信息
 */
function dr_calculate_reputation_with_userid($userid, $rep_settings = null, $user_histories = null)
{
	if ($rep_settings === null) {
		$rep_settings = dr_get_reputation_settings();
	}
	if ($user_histories === null) {
		$user_histories = dr_get_user_histories_stats_with_userid($userid);
	}

	$total_points = 1;
	foreach ($rep_settings as $action => $rep) {
		if ($rep !== 0) {
			$action_amount = $user_histories[$action];
			$total_points += $action_amount * $rep;
		}
	}

	# 更新用户的积分值
	dr_update_user_reputation_with_userid($userid, $total_points);
}

//dr_calculate_reputation_of_all();
